<template>
  <BasicDialog ref="basicDialog" :isVisible="isAlert" width="30%" :title="title" @handleSure="handleSure" :isShowSure="flag != 'dictType_look'">
    <template #content>
      <el-form ref="formRef" :model="formInfo" :rules="flag != 'dictType_look' ? rules : {}" label-width="120px">
        <el-form-item label="字典名称：" prop="dname">
          <el-input v-if="flag != 'dictType_look'" type="text" v-model.trim="formInfo.dname" placeholder="字典名称"
            clearable></el-input>
          <span v-else>{{ formInfo.dname }}</span>
        </el-form-item>
        <el-form-item label="字典key：" prop="dictKey">
          <el-input v-if="flag != 'dictType_look'" type="text" v-model.trim="formInfo.dictKey"
            placeholder="字典key" clearable></el-input>
          <span v-else>{{ formInfo.dictKey }}</span>
        </el-form-item>
      </el-form>
    </template>
  </BasicDialog>
</template>
<script lang='ts' setup>
import { FormInfo } from "@components/common/BasicForm/BasicFormTypes";
import type { FormRules, FormInstance } from 'element-plus';
import { dictTypeAdd, dictTypeEdit, getDictTypeById } from "@/request/apis/system/dictType"
const props = defineProps({
  info: {
    type: Object,
    default: () => {
      return {}
    }
  },
  flag: {
    type: String,
    default: ''
  },
  isAlert: {
    type: Boolean,
    default: false
  },
})

const $emits = defineEmits([
  "closeDialog"
])

// 提交表单校验
const formRef = ref<FormInstance>();
const basicDialog = ref();

async function handleSure() {
  await formRef.value.validate();
  basicDialog.value.changeLoading(true);

  try{
    if(props.flag == 'dictType_add'){//新增
      await dictTypeAdd(formInfo.value);
      $emits("closeDialog", 1);
      ElMessage.success("操作成功")
    }else if(props.flag == 'dictType_edit'){//修改
      await dictTypeEdit(formInfo.value);
      $emits("closeDialog", 1);
      ElMessage.success("操作成功")
    }else{//查看
      basicDialog.value.changeLoading(false);
      $emits("closeDialog", 0);
    }
  }catch(error){
    basicDialog.value.changeLoading(false);
  }
}

//表单数据 
let formInfo = ref<FormInfo>({});
// 表单校验规则
const rules = {
  dname: [{ required: true, message: "不能为空", trigger: "blur" }],
  dictKey: [{ required: true, message: "不能为空", trigger: "blur" }],
}
const title = ref("");
onMounted(async () => {
  if (props.flag == "dictType_add") {
    title.value = '新增'
  } else if (props.flag == "dictType_edit") {
    title.value = '修改'
    formInfo.value = await getDictTypeById(props.info.id)
  } else if (props.flag == "dictType_look") {
    title.value = '查看'
    formInfo.value = await getDictTypeById(props.info.id)
  }
})

</script>

<style scoped lang="scss"></style>